package com.taptech.doufu.net.retrofit.file;

import android.util.Log;

import com.taptech.doufu.net.retrofit.RxBus;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by Wyatt on 2017/10/19/019.
 */

public abstract class FileCallback implements Callback<ResponseBody> {

    /**
     * 订阅下载进度
     */
    private CompositeSubscription rxSubscriptions = new CompositeSubscription();

    /**
     * 目标文件存储路径
     */
    private String destFileDir;

    /**
     * 目标文件名称
     */

    private String destFileName;

    public FileCallback(String destFileDir, String destFileName) {
        this.destFileDir = destFileDir;
        this.destFileName = destFileName;
        subscribeLoadProgress();
    }

    /**
     * 成功后回调
     */
    public abstract void onSuccess(File file);

    /**
     * 下载过程回调
     */
    public abstract void onLoading(long curr, long total);

    /**
     * 请求成功后保存文件
     */
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        try {
            saveFile(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过ＩＯ流写入文件
     */
    public File saveFile(Response<ResponseBody> response){
        InputStream in ;
        FileOutputStream out ;
        File file = null;
        byte[] buf = new byte[2048];
        int len;
        try {
            File dir = new File(destFileDir);
            if (!dir.exists()) {
                //文件不存在，新建一个
                dir.mkdirs();
            }
            Log.d("FileCallBack", dir.exists() + "");
            in = response.body().byteStream();
            file = new File(dir, destFileName);
            out = new FileOutputStream(file);
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            //回调成功的接口
            onSuccess(file);
            unSubscribe();//取消订阅
            return file;
        }catch (IOException e){
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 订阅文件下载进度
     */
    private void subscribeLoadProgress() {
        rxSubscriptions.add(RxBus.getDefault()
                .toObservable(FileLoadingBean.class)
                .onBackpressureBuffer()
                .compose(RxJavaHelper.<FileLoadingBean>observeOnMainThread())
                .subscribe(new Action1<FileLoadingBean>() {
                    @Override
                    public void call(FileLoadingBean fileLoadingBean) {
                        onLoading(fileLoadingBean.getCurr(),fileLoadingBean.getTotal());
                    }
                }));
    }

    /**
     * 取消订阅,防止内存泄漏
     */
    private void unSubscribe() {
        if (!rxSubscriptions.isUnsubscribed()) {
            rxSubscriptions.unsubscribe();
        }
    }
}
